import json
import requests
from uuid import uuid4
import os

def upload_file(local_path):
    url = 'http://116.62.130.29/v1/files/upload'
    headers = {'Authorization': 'Bearer app-WqiQCDEUM0Hlm8Jvpj0jGtNu'}
    files = {("file", (str(uuid4())+'.pdf', open(local_path, "rb"), "application/pdf")),}
    data = {"user": "abc-123"}
    a = requests.post(url, headers=headers, files=files, json=data)
    return a.json()['id']

def uploads():
    ids = []
    for path in os.listdir("docs"):
        id = upload_file(os.path.join("docs", path))
        ids.append( id)
    return ids

def run_workflow(file_ids):
    l = []
    for id in file_ids:
        l.append({
                 "transfer_method": "local_file",
                 "upload_file_id": id,
                 "type": "document"
                })

    url = "http://116.62.130.29/v1/workflows/run"
    headers = {
        "Authorization": "Bearer app-WqiQCDEUM0Hlm8Jvpj0jGtNu",
        "Content-Type": "application/json"
    }
    data = {
            "inputs": {"files":l},
            "user": "abc-123"
    }
    return requests.post(url,headers=headers,json=data)


def parse_json(d):
    s = d['data']['outputs']['text']
    s = s.split('</think>')[1]
    s = s.replace('}\n{', '},{')
    s = s.replace('}\n\n{', '},{')
    s = '[' + s + ']'
    print(s)
    d = json.loads(s)
    with open('output.json', 'w+', encoding='utf-8') as f:
        json.dump(d, f, indent=4, ensure_ascii=False)

def do():
    ids = uploads()
    print(ids)
    res = run_workflow(ids)
    parse_json(res.json())

if __name__ == '__main__':
    do()